package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.util.UUIDUtils;
import org.apache.commons.io.IOUtils;
import org.apache.xmlbeans.impl.common.IOUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @Author: qingtao
 * @Date 2022/3/11 9:52
 */
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String path;

    @RequestMapping("/upload")
    public R <String> upload(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String fileExtName = filename.substring(filename.lastIndexOf("."));
        String newFilename = UUIDUtils.getUUID() + fileExtName;
        File dir = new File(path);
        if (!dir.exists()){
            dir.mkdir();
        }
        file.transferTo(new File(path + newFilename));
        return R.success(newFilename);
    }

    @RequestMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        FileInputStream inputStream = new FileInputStream(path + name);
        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.copy(inputStream,outputStream);
    }

}
